package red.stu.pconstraint.scanner;

import org.jetbrains.annotations.NotNull;
import red.stu.pconstraint.util.matcher.AntPathMatcher;
import red.stu.pconstraint.util.matcher.PathMatcher;

import java.util.List;

/**
 * xml文件资源扫描器
 * @author yihrmc @stu.red
 * @date 2019/11/18 13:40
 */
public class XmlScanner extends ResourceScanner<String> {

    private static final String FILE_SUFFIX = ".xml";

    private PathMatcher pathMatcher;
    private String pathPattern;

    public XmlScanner() {
        this(new AntPathMatcher(ResourceScanner.pathSeparator));
    }

    public XmlScanner(PathMatcher pathMatcher) {
        this.pathMatcher = pathMatcher;
    }

    @Override
    public synchronized List<String> scan(@NotNull String scanPath) {
//        if (!scanPath.startsWith(ResourceScanner.pathSeparator)) {
//            scanPath = ResourceScanner.pathSeparator + scanPath;
//        }
        if (pathMatcher.isPattern(scanPath)) {
            String patternPathRoot = getPatternPathRoot(scanPath);
            if (patternPathRoot != null) {
                this.pathPattern = scanPath;
                scanPath = patternPathRoot;
            }
        }
        List<String> xmlPathList = super.scan(scanPath);
        this.pathPattern = null;
        return xmlPathList;
    }

    @Override
    protected String handleScanFile(String filePath) {
        if (filePath.endsWith(FILE_SUFFIX)) {
            if (pathPattern != null) {
                if (pathMatcher.match(pathPattern, filePath)) {
                    return filePath;
                }
            } else {
                return filePath;
            }
        }
        return null;
    }

    /**
     * 获取通配符路径根路径
     * @param patternPath 统配路径
     * @return
     */
    public static String getPatternPathRoot(String patternPath) {
        if (patternPath.indexOf('\\') != -1) {
            patternPath = patternPath.replaceAll("\\\\", ResourceScanner.pathSeparator);
        }
        // isPattern
        int i1 = patternPath.indexOf('?');
        int i2 = patternPath.indexOf("*");
        int minIndex;
        if (i1 != -1 && i2 != -1) {
            minIndex = Math.min(i1, i2);
        } else if (i1 != -1) {
            minIndex = i1;
        } else if (i2 != -1) {
            minIndex = i2;
        } else {
            return null;
        }
        if (minIndex == 0) {
            return ResourceScanner.pathSeparator;
        }
        String tempPathSeparator = patternPath.substring(minIndex - 1, minIndex);
        String tempBasePath = patternPath.substring(0, minIndex - 1);
        if (!ResourceScanner.pathSeparator.equals(tempPathSeparator)) {
            int separatorIndex = tempBasePath.lastIndexOf(ResourceScanner.pathSeparatorChar);
            if (separatorIndex <= 0) {
                return ResourceScanner.pathSeparator;
            }
            tempBasePath = patternPath.substring(0, separatorIndex);
        }
        return tempBasePath;
    }

}
